using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security;
using System.Xml;
using Gizmox.WebGUI.Common.Resources;
using Gizmox.WebGUI.Forms;
using QueryBuilder;
using TVC.Layout;
using TVC.Modules.Ddb;
using Gizmox.WebGUI.Common.Gateways;
using DTO;


namespace TVC
{
    /// <summary>
    /// Summary description for MainForm.
    /// </summary>
    [Serializable()]
    public class MainForm : BaseForm
    {
        public const string prefixText = "txt";
        public const string prefixPic = "pib";
        public const string prefixLab = "lbl";
        public const string prefixCol = "col";
        public const string prefixCom = "cbo";
        public const string prefixMulti = "mcb";
        public const string strApproval = "Approved";
        public const string strReject = "Rejected";
        public const string strClose = "Close";
        public const string strPending = "Pending";
        public static string ServerPath = "";
        private readonly DataSet _dsMain = new DataSet("TVC");
        private DataTable _FormPara = new DataTable("FormPara");
        private static string _ReportConnectString = "";
        private static string _HLConnect = "";
        private static string _TVCConnectImportR = "";
        private static string _AppConnectString = "";
        public static string _DateFormatString = "yyyy-MM-dd";
        public TVC.Modules.Act.Events Events;
        int idAllowEditLanguage = 1;
        int idAdminData = 2;
        public static string pathinfo;
        public string SUNDB { get; set; }
        public string Language
        {
            get { return _language; }
            set { _language = value; }
        }
        public static string AppConnectString
        {
            get { return MainForm._AppConnectString; }
            set { MainForm._AppConnectString = value; }
        }

        public static string ReportConnectString
        {
            get { return MainForm._ReportConnectString; }
            set { MainForm._ReportConnectString = value; }
        }

        public static string HLConnect
        {
            get { return MainForm._HLConnect; }
            set { MainForm._HLConnect = value; }
        }
        public static string TVCConnectImportR
        {
            get { return MainForm._TVCConnectImportR; }
            set { MainForm._TVCConnectImportR = value; }
        }
        public DataTable FormPara
        {
            get { return _FormPara; }
            set { _FormPara = value; }
        }


        //public static DataSet DsMain
        //{
        //    get { return MdiMainForm._dsMain; }
        //    set { MdiMainForm._dsMain = value; }
        //}
        protected HeaderedPanel mobjPanelCategory;
        private string _permis = "";

        public string Permission
        {
            get { return _permis; }
            set
            {
                if (_permis != value)
                    _permis = value;
            }
        }
        public static MainForm Current { get; set; }
        public MainForm()
        {
            Current = this;
            string sErr = "";

            clsConfigurarion.ServerDirPath = MainForm.ServerPath = Context.HttpContext.Request.MapPath("/");
            Application.ThreadException += Application_ThreadException;
            Load += MainForm_Load;
            //PODInfo.USER_ID = "Admin";
            //PODInfo.EMP_ID = "Admin";

            if (!_FormPara.Columns.Contains("P1"))
                _FormPara.Columns.Add("P1");
            if (!_FormPara.Columns.Contains("P2"))
                _FormPara.Columns.Add("P2");
            if (!_FormPara.Columns.Contains("P3"))
                _FormPara.Columns.Add("P3");
            if (!_FormPara.Columns.Contains("P4"))
                _FormPara.Columns.Add("P4");
            if (!_FormPara.Columns.Contains("P5"))
                _FormPara.Columns.Add("P5");
            if (!_FormPara.Columns.Contains("P6"))
                _FormPara.Columns.Add("P6");
            if (!_FormPara.Columns.Contains("P7"))
                _FormPara.Columns.Add("P7");
            if (!_FormPara.Columns.Contains("P8"))
                _FormPara.Columns.Add("P8");
            if (!_FormPara.Columns.Contains("P9"))
                _FormPara.Columns.Add("P9");
            if (!_FormPara.Columns.Contains("P10"))
                _FormPara.Columns.Add("P10");
            if (!_FormPara.Columns.Contains("L1"))
                _FormPara.Columns.Add("L1");

            InitConnection();

        }

        private void InitConnection()
        {
            MainForm._AppConnectString = Properties.Settings.Default.TVCConnectStringDes;
            MainForm._ReportConnectString = Properties.Settings.Default.TVCConnectString;
            MainForm._TVCConnectImportR = Properties.Settings.Default.TVCConnectStringDes;
            MainForm._HLConnect = Properties.Settings.Default.HLConnectString;

            Report.ReportGenerator.ConnectionList.Add(new Report.ReportGenerator.ConnectItem() { ID = "HLV", ConnectString = Properties.Settings.Default.TVCConnectStringDes, Type = "AP" });
            Report.ReportGenerator.ConnectionList.Add(new Report.ReportGenerator.ConnectItem() { ID = "PRV", ConnectString = Properties.Settings.Default.HLConnectStringDes, Type = "AP" });
            Report.ReportGenerator.ConnectionList.Add(new Report.ReportGenerator.ConnectItem() { ID = "HVJ", ConnectString = Properties.Settings.Default.HLConnectStringDes, Type = "AP" });
            Report.ReportGenerator.ConnectionList.Add(new Report.ReportGenerator.ConnectItem() { ID = "OTH", ConnectString = Properties.Settings.Default.OTHERConnectStringDes, Type = "AP" });
        }

        protected override void InitializeWorkspace()
        {
            //this.IsMdiContainer = true;

            _mobjTabWorkSpace = new WorkspaceTabs();
            _mobjTabWorkSpace.ClientBehavior = TabControlClientBehavior.DrawingOptimized;
            _mobjTabWorkSpace.Dock = DockStyle.Fill;
            _mobjTabWorkSpace.Alignment = TabAlignment.Bottom;
            _mobjTabWorkSpace.CloseClick += new EventHandler(_mobjTabWorkSpace_CloseClick);
            //_mobjTabWorkSpace.SelectedIndexChanged += new EventHandler(_mobjTabWorkSpace_SelectedIndexChanged);
            Controls.Add(_mobjTabWorkSpace);
            //  mobjPanelCategory = CreatePanelWorkSpace();
            //  Controls.Add(mobjPanelCategory);
        }

        void _mobjTabWorkSpace_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabPage tab = _mobjTabWorkSpace.SelectedTab;
            if (tab != null)
            {
                //if (tab.Name == "Movement Entry")
                //{
                //    if (mme is Modules.ModuleParent)
                //    {
                //        ((Modules.ModuleParent)mme).reloadReference();
                //    }
                //}
                //if (tab.Name == "Item Records")
                //{
                //    if (imr is Modules.ModuleParent)
                //    {
                //        ((Modules.ModuleParent)imr).reloadReference();
                //    }
                //}
                foreach (WorkspaceTab t in _mobjTabWorkSpace.TabPages)
                {
                    t.ForeColor = Color.Black;
                    //  t.Font = new Font(this.Font, FontStyle.Regular);
                }
                tab.ForeColor = Color.Red;
            }

            //  tab.Font = new Font(this.Font, FontStyle.Regular);
        }



        void _mobjTabWorkSpace_CloseClick(object sender, EventArgs e)
        {
            TabPage tab = _mobjTabWorkSpace.SelectedTab;
            _mobjTabWorkSpace.TabPages.Remove(tab);
            tab.Dispose();
            //_mobjTabWorkSpace.SelectedTab.dis
        }

        protected override void AddWorspaceControl(Control objControl, ToolBar toolbar = null)
        {
            WorkspaceTab Curtab = null;
            foreach (WorkspaceTab tab in _mobjTabWorkSpace.TabPages)
            {
                if (tab.Name == objControl.Text)
                {
                    Curtab = tab;

                    break;
                }
            }

            if (Curtab == null)
            {
                if (objControl is Modules.ModuleParent)
                {
                    ((Modules.ModuleParent)objControl).MainForm = this;
                    ((Modules.ModuleParent)objControl).TbarLocal = toolbar;

                }
                if (objControl.Text == "Movement Entry")
                {
                    mme = objControl;
                }
                if (objControl.Text == "Item Records")
                {
                    imr = objControl;
                }
                mobjPanelCategory = CreatePanelWorkSpace();

                mobjPanelCategory.Controls.Add(toolbar);

                mobjPanelCategory.Controls.Add(objControl);

                WorkspaceTab tabControl = new WorkspaceTab(objControl.Text);
                tabControl.Name = objControl.Text;
                tabControl.Controls.Add(mobjPanelCategory);

                _mobjTabWorkSpace.TabPages.Add(tabControl);
                Curtab = tabControl;
            }

            _mobjTabWorkSpace.SelectedTab = Curtab;
        }
        private HeaderedPanel CreatePanelWorkSpace()
        {
            HeaderedPanel mobjPanelCategory = new HeaderedPanel();

            // 
            // mobjPanelCategory
            // 
            Button btChangeScreen = new Button();
            btChangeScreen.Size = new System.Drawing.Size(22, 22);
            btChangeScreen.FlatStyle = FlatStyle.Flat;
            //btChangeScreen.FlatAppearance = new FlatButtonAppearance();
            btChangeScreen.FlatAppearance.BorderSize = 0;
            //btChangeScreen.Padding = new Gizmox.WebGUI.Forms.Padding(0);
            // btChangeScreen.Image = new IconResourceHandle("maximize.png");
            btChangeScreen.BackgroundImage = new IconResourceHandle("maximize.png");
            btChangeScreen.BackgroundImageLayout = ImageLayout.Center;
            //btChangeScreen.BackColor = Color.Transparent;
            mobjPanelCategory.BackgroundImageLayout = ImageLayout.None;
            // mobjPanelCategory.Controls.Add(mobjCommandText);
            mobjPanelCategory.ClientSize = new Size(482, 694);
            mobjPanelCategory.CustomStyle = "HeaderedPanel";
            mobjPanelCategory.Dock = DockStyle.Fill;
            mobjPanelCategory.Location = new Point(243, 28);
            mobjPanelCategory.Name = "mobjPanelCategory";
            //mobjPanelCategory.PanelType = PanelType.Titled;
            mobjPanelCategory.Size = new Size(482, 694);
            mobjPanelCategory.TabIndex = 2;
            mobjPanelCategory.Text = "Category";
            mobjPanelCategory.AutoScroll = true;
            mobjPanelCategory.Header = new Panel();
            mobjPanelCategory.Header.Size = new System.Drawing.Size(200, 22);
            mobjCommandText.Dock = DockStyle.Fill;
            mobjPanelCategory.Header.Controls.Add(mobjCommandText);
            mobjPanelCategory.Header.Controls.Add(btChangeScreen);
            btChangeScreen.Dock = DockStyle.Right;
            // mobjPanelCategory.Header = btChangeScreen;

            // mobjPanelCategory.BringToFront();

            btChangeScreen.Click += delegate
            {
                if (ChangeScreen()) btChangeScreen.BackgroundImage = new IconResourceHandle("maximize.png");

                else btChangeScreen.BackgroundImage = new IconResourceHandle("normal.png");
                //   mobjMainMenu.Visible = !mobjMainMenu.Visible;
                //mobjCommandText.Visible = mobjMainMenu.Visible;
                // mobjPanelCategories.Visible = mobjMainMenu.Visible;
            };
            return mobjPanelCategory;
        }


        protected override void ClearWorspace()
        {
            //try
            //{
            //    mobjPanelCategory.Controls.Clear();
            //}
            //catch
            //{
            //}
        }


        protected override void SetTitle(string title)
        {
            mobjPanelCategory.Text = title;
        }



        /// <summary>
        /// Initializes the catalog category node.
        /// </summary>
        /// <param name="objCategoryNode">The obj category node.</param>
        /// <param name="objNodeDefinition">The obj node definition.</param>
        private static void InitializeCatalogCategoryNode(CategoryNode objCategoryNode, XmlElement objNodeDefinition, string language, string Permission, DTO.PODInfo pod)
        {

            string sErr = "";
            BUS.csreportgroupsControl rgdCtr = new BUS.csreportgroupsControl();
            DataTable dt = rgdCtr.GetGroupbyDA("TVC", pod.ROLE_ID, ref sErr);
            int i = 0;

            foreach (XmlElement objSubCategoryDefinition in objNodeDefinition.SelectNodes("CatalogNode"))
            {
                // The sub category node
                CategoryNode objSubCategoryNode = null;

                // If has a module defined

                string idhandle = objSubCategoryDefinition.GetAttribute("IdHandle");

                if (IsPermis(idhandle, Permission))// idhandle == null || idhandle == "" || Convert.ToInt32(idhandle) >= Permission.Length || Permission[Convert.ToInt32(idhandle)] == 'Y')
                {
                    if (objSubCategoryDefinition.GetAttribute("Label") == "Group" && dt.Rows.Count > 0)
                    {
                        for (i = 0; i < dt.Rows.Count; i++)
                        {
                            string strValue = "";
                            string strLabel = dt.Rows[i]["Name"].ToString();
                            string strModule = "";
                            string strAddress = "";
                            objSubCategoryNode = objCategoryNode.AddCategory(strLabel, strModule, strAddress, language);


                            BUS.csreportgroupdetailControl ctrdel = new BUS.csreportgroupdetailControl();
                            DataTable dtreport = ctrdel.GetbyGroup(dt.Rows[i]["DB"].ToString(), dt.Rows[i]["ReportGroup"].ToString(), pod.Business_ID, ref sErr);
                            for (int j = 0; j < dtreport.Rows.Count; j++)
                            {
                                strValue = dtreport.Rows[j]["reportcode"].ToString();
                                strLabel = dtreport.Rows[j]["DESCRIPTN"].ToString();
                                strModule = "QRS";
                                strAddress = "TVC.Modules.Rep.QRS";
                                Type objSubCatalogModuleMappedType = CatalogSettings.GetCatalogModuleTypeByModuleName(strModule);
                                //objSubCatalogModuleMappedType.FullName = dtreport.Rows[j]["reportcode"].ToString();
                                CategoryNode nodeReport = objSubCategoryNode.AddCategory(strLabel, strModule, objSubCatalogModuleMappedType, strAddress, language);
                                nodeReport.Command = "id=" + strValue;

                            }
                        }
                    }
                    else
                    {

                        if (objSubCategoryDefinition.HasAttribute("Module"))
                        {

                            Type objSubCatalogModuleMappedType = CatalogSettings.GetCatalogModuleTypeByModuleName(objSubCategoryDefinition.GetAttribute("Module"));
                            if (objSubCatalogModuleMappedType != null)
                            {
                                objSubCategoryNode = objCategoryNode.AddCategory(objSubCategoryDefinition.GetAttribute("Label"), objSubCategoryDefinition.GetAttribute("Module"), objSubCatalogModuleMappedType, objSubCategoryDefinition.GetAttribute("Address"), language);
                            }

                            // Try to get module type definition

                        }
                        else
                        {
                            //if (idhandle == null || idhandle == "" || Convert.ToInt32(idhandle) >= Permission.Length || Permission[Convert.ToInt32(idhandle)] == 'Y')
                            objSubCategoryNode = objCategoryNode.AddCategory(objSubCategoryDefinition.GetAttribute("Label"), objSubCategoryDefinition.GetAttribute("Module"), objSubCategoryDefinition.GetAttribute("Address"), language);

                        }
                        //}
                    }

                    if (objSubCategoryNode != null)
                    {
                        // If is a defalut module
                        if (objSubCategoryDefinition.GetAttribute("Default") == "True")
                        {
                            objSubCategoryNode.SetDefault();
                        }
                        objSubCategoryNode.Command = objSubCategoryDefinition.GetAttribute("Command");
                    }

                    InitializeCatalogCategoryNode(objSubCategoryNode, objSubCategoryDefinition, language, Permission, pod);
                }



            }

        }


        /// <summary>
        /// Initializes the catalog sections.
        /// </summary>
        private void InitializeCatalogSections()
        {
            // Loop all catalog sections
            foreach (XmlElement objCatalogSection in CatalogSettings.CatalogSections)
            {
                // The section category node
                CategoryNode objCategoryNode = null;

                // If has icon
                string idhandle = objCatalogSection.GetAttribute("IdHandle");


                if (idhandle == null || idhandle == "" || IsPermis(Convert.ToInt32(idhandle)))
                {
                    if (objCatalogSection.HasAttribute("Icon"))
                    {

                        // Create section
                        //if (idhandle == null || idhandle == "" || Convert.ToInt32(idhandle) >= Permission.Length || Permission[Convert.ToInt32(idhandle)] == 'Y')
                        objCategoryNode = RootCategory.AddCategory(objCatalogSection.GetAttribute("Label"), objCatalogSection.GetAttribute("Module"), objCatalogSection.GetAttribute("Icon"), objCatalogSection.GetAttribute("Address"), _language);

                    }
                    else
                    {
                        //if (idhandle == null || idhandle == "" || Convert.ToInt32(idhandle) >= Permission.Length || Permission[Convert.ToInt32(idhandle)] == 'Y')
                        //

                        objCategoryNode = RootCategory.AddCategory(objCatalogSection.GetAttribute("Label"), objCatalogSection.GetAttribute("Module"), objCatalogSection.GetAttribute("Address"), _language);




                    }
                    objCategoryNode.Command = objCatalogSection.GetAttribute("Command");
                    InitializeCatalogCategoryNode(objCategoryNode, objCatalogSection, Language, Permission, PODInfo);
                }

                // Initialize recursivly

            }


        }

        void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            AddLog("error", string.Format("{0}:({1}@{2}):{3}:{4}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), PODInfo.USER_ID, DB, e.Exception.TargetSite.Name + "|" + e.Exception.TargetSite.ToString(), e.Exception.Message + "\n" + e.Exception.Source + "\n" + e.Exception.StackTrace));
            MessageBox.Show("Your process has something WRONG! Please contact system administrator \n Please login again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, ErrorHandle, true);
        }
        private void ErrorHandle(object form, EventArgs e)
        {
            Context.Session.IsLoggedOn = false;
            VWGContext.Current.HostContext.HttpContext.Session.Abandon();
        }
        public static void AddLog(string type, string message)
        {
            string _path = ServerPath + "local_log";
            if (message == "") return;
            if (_path == "")
                return;
            else
            {
                if (!Directory.Exists(_path))
                    Directory.CreateDirectory(_path);
            }
            GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
            int week = cal.GetWeekOfYear(DateTime.Today, CalendarWeekRule.FirstDay, DayOfWeek.Monday);

            string erroFile = String.Format("{0}\\{1}{2}.log", _path, type, DateTime.Today.Year.ToString("0000") + week.ToString("000"));
            //System.IO.StreamWriter sw = new System.IO.StreamWriter(erroFile);
            if (!File.Exists(erroFile))
            {
                using (StreamWriter swt = File.CreateText(erroFile))
                {
                    swt.WriteLine(message);
                }

            }
            else
            {
                using (FileStream file = new FileStream(erroFile, FileMode.Append))
                {
                    using (StreamWriter sw = new StreamWriter(file))
                    {
                        sw.WriteLine(message);
                    }
                }
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            CoreCommonControl.SetConnection(MainForm.ReportConnectString);
            if (!Context.Session.IsLoggedOn)
            {
                Context.Redirect("~/frmLogon.wgx");
                return;
            }
            string sErr = "";
            //SQLBuilder.SetConnection(MainForm._AppConnectString);
            DTO.PODInfo INFO = (DTO.PODInfo)Session["User"];
            BUS.POPControl ctr = new BUS.POPControl();
            DTO.POPInfo popInf = ctr.Get(INFO.ROLE_ID, DB, ref sErr);
            if (popInf.ROLE_ID == "") popInf = ctr.Get(INFO.ROLE_ID, "", ref sErr);

            Permission = popInf.PERMISSION;

            if (INFO != null) PODInfo = INFO;
            //BUS.POPControl contr = new BUS.POPControl();
            //Permission = contr.Get(info.ROLE_ID, DB, ref sErr).PERMISSION.ToString();
            SetLogon(String.Format("Database : {3} User: {0} - {1} Role:{2}", PODInfo.USER_ID, PODInfo.USER_NAME, PODInfo.ROLE_ID, PODInfo.Business_Name));
            LoadLanguage(Language);
            InitializeCatalogSections();
            if (IsPermis(idAllowEditLanguage))
                AllowEditLanguage();
            SetMsg(sErr);
            LoadImage();
            Events = new Modules.Act.Events(this);
            if (INFO.Business_ID == "HL") SUNDB = Properties.Settings.Default.SUNHL;
            else SUNDB = Properties.Settings.Default.SUNHV;
            INFO.Database = SUNDB;
            Context.Session["User"] = INFO;
            SunSync();
        }
        private void SunSync()
        {
            if (string.IsNullOrEmpty(PODInfo.Business_ID)) return;
            // SupplierSync();
            //VendorSync();
            //ContractSync();
            //BudgetSync();
        }

        public string SupplierSync()
        {
            string sErr = string.Empty;
            string ConnecSUN = MainForm.HLConnect;
            BUS.SSRFANVControl anvCtr = new BUS.SSRFANVControl();
            DataTable dt = anvCtr.GetAll_SSRFANVBU("M6", SUNDB, ref sErr, MainForm.HLConnect);

            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //item[]
                    //string SQL = "NSERT INTO TVC_LOOKUP (TB, TBField, Code, Lookup, Description) values ( 'TVC_MFMOV' , 'Supplier', '" + item[2] + "', '" + item[3] + "', '" + item[5] + "' ) ";
                    BUS.TVC_LOOKUPControl ctr = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
                    DTO.TVC_LOOKUPInfo info = new DTO.TVC_LOOKUPInfo("TVC_MFMOV", "Supplier", dt.Rows[i]["CODE"].ToString().Trim(), dt.Rows[i]["LOOKUP"].ToString().Trim(), dt.Rows[i]["NAME"].ToString().Trim(), "");
                    ctr.Add(SUNDB, info, ref sErr);
                }
            }
            return sErr;
        }
        /*
        public string BudgetSync()
        {
            string sErr = "";
            BUS.BudgetsControl ctr = new BUS.BudgetsControl();
            BUS.SSRFANVControl ctrOrgan = new BUS.SSRFANVControl();
            string strSUN_DB = DB;
            string connect = MainForm.SUNConnect;
            var DatabaseInfo = Context.Session["DatabaseInfo"] as DBAInfo;
            string tCode = DatabaseInfo.PARAM_4 != "" ? DatabaseInfo.PARAM_4 : Properties.Settings.Default.Budget;
            DataTable dt = ctrOrgan.GetAll_SSRFANVBU(tCode, strSUN_DB, ref sErr, connect, Properties.Settings.Default.SUNVersion);

            if (dt.Rows.Count > 0)
            {
                ctr.BeginTransaction(ref sErr);
                foreach (DataRow r in dt.Rows)
                {
                    DTO.BudgetsInfo inf = new DTO.BudgetsInfo()
                    {
                        DTB = DB,
                        Contract = r["CODE"].ToString(),
                        Desc = r["NAME"].ToString(),
                        aYear = DateTime.Today.Year,
                        CreatedBy = PODInfo.USER_ID
                    };

                    sErr = ctr.Synchronize(DB, inf);
                    if (sErr != "") break;

                }
                if (sErr != "")
                {
                    MainForm.AddLog("error", sErr);
                    ctr.RollbackTransaction(ref     sErr);
                }
                else
                {
                    ctr.CommitTransaction(ref sErr);
                }
            }
            return sErr;
        }

        public string ContractSync()
        {
            string sErr = "";
            BUS.ContractControl ctr = new BUS.ContractControl();
            BUS.SSRFANVControl ctrOrgan = new BUS.SSRFANVControl();
            string strSUN_DB = DB;
            string connect = MainForm.SUNConnect;
            var DatabaseInfo = Context.Session["DatabaseInfo"] as DBAInfo;
            string tCode = DatabaseInfo.PARAM_3 != "" ? DatabaseInfo.PARAM_3 : Properties.Settings.Default.Contract;
            DataTable dt = ctrOrgan.GetAll_SSRFANVBU(tCode, strSUN_DB, ref sErr, connect, Properties.Settings.Default.SUNVersion);

            if (dt.Rows.Count > 0)
            {
                ctr.BeginTransaction(ref sErr);
                foreach (DataRow r in dt.Rows)
                {
                    DTO.ContractInfo inf = new DTO.ContractInfo()
                    {
                        DTB = DB,
                        Contract = r["CODE"].ToString(),
                        Desc = r["NAME"].ToString()
                    };

                    sErr = ctr.Synchronize(DB, inf);
                    if (sErr != "") break;

                }
                if (sErr != "")
                {
                    MainForm.AddLog("error", sErr);
                    ctr.RollbackTransaction(ref sErr);
                }
                else
                {
                    ctr.CommitTransaction(ref sErr);
                }
            }
            return sErr;
        }
        
        public string VendorSync()
        {
            string sErr = "";
            BUS.VENDORControl ctr = new BUS.VENDORControl();
            string strSUN_DB = DB;
            string connect = MainForm.SUNConnect;
            var DatabaseInfo = Context.Session["DatabaseInfo"] as DBAInfo;
            string tCode = DatabaseInfo.PARAM_2 != "" ? DatabaseInfo.PARAM_2 : Properties.Settings.Default.Vendor;
            DataTable dt = ctr.GetAll_VENDORT(strSUN_DB, tCode, ref sErr, connect, Properties.Settings.Default.SUNVersion);
            DTO.VENDORInfo inf;
            if (dt.Rows.Count > 0)
            {
                ctr.BeginTransaction(ref sErr);
                foreach (DataRow r in dt.Rows)
                {
                    inf = new DTO.VENDORInfo(r);
                    inf.VendorCode = inf.VendorCode.Trim();
                    inf.VendorName = inf.VendorName.Trim();
                    sErr = ctr.Synchronize(DB, inf);
                    if (sErr != "") break;

                }
                if (sErr != "")
                {
                    MainForm.AddLog("error", sErr);
                    ctr.RollbackTransaction(ref sErr);
                }
                else
                {
                    ctr.CommitTransaction(ref sErr);
                }
            }
            return sErr;
        }
         */

        protected override void AllowEditLanguage()
        {
            base.AllowEditLanguage();
            mobjPanelCategory.DoubleClick += mobjPanelCategory_DoubleClick;
            ContextMenu menu = new ContextMenu();
            MenuItem it = new MenuItem("Edit Language");
            menu.MenuItems.Add(it);
            it.Tag = "LANG";
            //mobjToolBarMain.ContextMenu = menu;
            //mobjToolBarMain.MenuClick += mobjToolBarMain_MenuClick;
        }

        void mobjToolBarMain_MenuClick(object objSource, MenuItemEventArgs objArgs)
        {
            if (objArgs.MenuItem.Tag == "LANG")
                UpdateToolBarModuleLanguage(objSource, objArgs);
        }
        public DataTable LoadQDSource(string db, DTO.CategoryInfo cateinfo)
        {
            if (cateinfo.QdCode == "")
                return null;

            SQLBuilder sqlBuilder = SQLBuilder.LoadSQLBuilderFromDataBase(cateinfo.QdCode, db, "");
            sqlBuilder.StrConnectDes = MainForm._AppConnectString;
            DataTable dt = sqlBuilder.BuildDataTable("");
            foreach (Node node in sqlBuilder.SelectedNodes)
            {
                if (node.Code == cateinfo.NodeCode)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Code";
                        dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
                    }
                }
                if (node.Code == cateinfo.NodeDesc)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Description";
                    }
                }
                if (node.Code == cateinfo.NodeLookup)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Lookup";
                    }
                }
                if (node.Code == cateinfo.NodeStatus)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Status";
                    }
                }
            }
            try
            {
                dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
            }
            catch { }
            return dt;
        }
        public DataTable LoadQDSource(string db, DTO.CategoryInfo cateinfo, Dictionary<string, string> myparams)
        {
            if (cateinfo.QdCode == "")
                return null;

            SQLBuilder sqlBuilder = SQLBuilder.LoadSQLBuilderFromDataBase(cateinfo.QdCode, db, "");
            foreach (Filter x in sqlBuilder.Filters)
                foreach (KeyValuePair<string, string> it in myparams)
                {
                    x.FilterFrom = x.ValueFrom = x.ValueFrom.Replace("{" + it.Key + "}", it.Value);
                    x.FilterTo = x.ValueTo = x.ValueTo.Replace("{" + it.Key + "}", it.Value);
                }

            sqlBuilder.StrConnectDes = MainForm._AppConnectString;
            DataTable dt = sqlBuilder.BuildDataTable("");
            foreach (Node node in sqlBuilder.SelectedNodes)
            {
                if (node.MyCode == cateinfo.NodeCode)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Code";
                        dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
                    }
                }
                if (node.MyCode == cateinfo.NodeDesc)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Description";
                    }
                }
                if (node.MyCode == cateinfo.NodeLookup)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Lookup";
                    }
                }
                if (node.MyCode == cateinfo.NodeStatus)
                {
                    if (dt.Columns.Contains(node.Description))
                    {
                        dt.Columns[node.Description].ColumnName = "Status";
                    }
                }
            }
            try
            {
                dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
            }
            catch { }
            return dt;
        }
        private void UpdateToolBarModuleLanguage(object objSource, MenuItemEventArgs objArgs)
        {
            if (objSource is ToolBar)
            {
                ToolBar tool = objSource as ToolBar;
                HeaderedPanel control = tool.Parent as HeaderedPanel;
                if (control.Controls.Count == 2)
                {
                    ToolBarButton btn = objArgs.Source as ToolBarButton;
                    frmInputData frm = new frmInputData();
                    frm.Default = btn.Text;
                    frm.FormClosed += (form, args) =>
                    {
                        if (((Form)form).DialogResult == DialogResult.OK)
                        {
                            if (btn.Text != "") btn.Text = frm.valuereturn;
                            btn.ToolTipText = frm.valuereturn;
                            clsConfigurarion.SetLabel(control.Controls[0].ToString(), btn.Name, frm.valuereturn, Language);
                        }
                    };
                    frm.ShowDialog();
                }
            }
        }

        void mobjPanelCategory_DoubleClick(object sender, EventArgs e)
        {
            //UpdateTitleModuleLanguage(sender);
        }
        protected void UpdateTitleModuleLanguage(object obj)
        {
            if (obj is HeaderedPanel)
            {
                HeaderedPanel control = obj as HeaderedPanel;
                if (control.Controls.Count == 2)
                {
                    frmInputData frm = new frmInputData();
                    frm.Default = control.Text;
                    frm.FormClosed += (form, args) =>
                    {
                        if (((Form)form).DialogResult == DialogResult.OK)
                        {
                            control.Text = frm.valuereturn;
                            TreeNode node = GetSelectedNode();
                            node.Text = frm.valuereturn;
                            if (control.Controls[0] is TVC.Categories.LogicalCategory)
                            {
                                TVC.Categories.LogicalCategory logicNode = control.Controls[0] as TVC.Categories.LogicalCategory;
                                clsConfigurarion.SetLabel(logicNode.Address, "", control.Text, Language);
                            }
                            else
                                clsConfigurarion.SetLabel(control.Controls[0].ToString(), "", control.Text, Language);
                        }
                    };
                    frm.ShowDialog();
                }
            }

        }


        #region My Method
        public string TVCFormatData(DataTable dt, string sErr, string _strType)
        {

            return sErr;
        }

        public void LoadDataTable(string tableName)
        {
            string sErr = "";
            DataTable dt = new DataTable();
            switch (tableName)
            {
                #region Dashboard
                case "Vendor":
                    BUS.VENDORControl ctrVendor = new BUS.VENDORControl();
                    dt = ctrVendor.GetAll_VENDOR(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "Employee":
                    BUS.EmployeeControl ctrEmployee = new BUS.EmployeeControl();
                    dt = ctrEmployee.GetAll_Employee(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "Budget":
                    BUS.BudgetsControl ctrBudget = new BUS.BudgetsControl();
                    dt = ctrBudget.GetAll_Budgets(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "Requisition":
                    BUS.PurchaseRequisitionControl ctrRequi = new BUS.PurchaseRequisitionControl();
                    dt = ctrRequi.GetAll_PurchaseRequisition(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "ExpenseClaim":
                    BUS.ExpenseClaimControl ctrExpenseClaim = new BUS.ExpenseClaimControl();
                    dt = ctrExpenseClaim.GetAll_ExpenseClaim(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "Invoice":
                    BUS.InvoiceRegisterControl ctrInvoice = new BUS.InvoiceRegisterControl();
                    dt = ctrInvoice.GetAll_InvoiceRegister(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "Contract":
                    BUS.ContractControl ctrContract = new BUS.ContractControl();
                    dt = ctrContract.GetAll_Contract(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "DDB":
                    BUS.LIST_GADGETControl ddbCtr = new BUS.LIST_GADGETControl();
                    dt = ddbCtr.GetAll(_db, PODInfo.USER_ID, ref sErr);
                    BUS.LIST_DAControl daCtr = new BUS.LIST_DAControl();
                    DataTable dtPermision = daCtr.GetPermissionByRole(PODInfo.ROLE_ID, ref sErr);
                    //if (dtPermision.Rows.Count == 0)
                    //    dt.Rows.Clear();
                    for (int i = dt.Rows.Count - 1; i >= 0; i--)
                    {
                        DTO.LIST_GADGETInfo testInf = new DTO.LIST_GADGETInfo(dt.Rows[i]);
                        string flag = "";
                        bool ie = true;
                        foreach (DataRow row in dtPermision.Rows)
                        {
                            if (testInf.DataGroup.Trim() != "")
                            {
                                if (testInf.DataGroup == row["DAG_ID"].ToString())
                                {
                                    flag = row["EI"].ToString();
                                }
                                else if (row["EI"].ToString() == "I")
                                {
                                    ie = false;
                                }
                            }
                        }
                        if ((flag == "" && ie) || flag == "I")
                        {
                        }
                        else
                        {
                            dt.Rows.Remove(dt.Rows[i]);
                        }

                    }
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.LIST_GADGETInfo.Field.ID.ToString()] };
                    break;
                #endregion

                #region Common
                case "IHB":
                    //BUS.TVC_MFMOVControl IHBCtr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
                    //dt = IHBCtr.GetHold("Y", ref sErr);
                    //dt.TableName = tableName;
                    //if (!IsContainsTables(tableName))
                    //{
                    //    _dsMain.Tables.Add(dt.Copy());

                    //}
                    //else
                    //{
                    //    _dsMain.Tables.Remove(tableName);
                    //    _dsMain.Tables.Add(dt.Copy());
                    //}
                    //if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                    //    _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.TVC_MFMOVInfo.Field.Code.ToString()] };
                    break;
                case "MME":
                    BUS.TVC_MFMOVControl MMECtr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
                    dt = MMECtr.GetHold(SUNDB, "Y", ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.TVC_MFMOVInfo.Field.Code.ToString()] };
                    break;
                case "MMQ":
                    BUS.TVC_MFMOVControl MMQCtr = new BUS.TVC_MFMOVControl(PODInfo.Business_ID);
                    dt = MMQCtr.GetHold(SUNDB, "All", ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.TVC_MFMOVInfo.Field.Code.ToString()] };
                    break;
                case "MMT":
                    BUS.TVC_MVPControl MVPCtr = new BUS.TVC_MVPControl(PODInfo.Business_ID);
                    dt = MVPCtr.GetAll(SUNDB, ref sErr);
                    dt.TableName = "MMT";
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.TVC_MVPInfo.Field.Code.ToString()] };
                    break;
                case "RGD":
                    BUS.csreportgroupsControl rgdCtr = new BUS.csreportgroupsControl();
                    dt = rgdCtr.GetAll(ref sErr);
                    dt.TableName = "RGD";
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.csreportgroupsInfo.Field.ReportGroup.ToString()] };
                    break;
                case "TASK":
                    BUS.LIST_TASKControl taskCtr = new BUS.LIST_TASKControl();
                    dt = taskCtr.GetAll(DB, ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.LIST_TASKInfo.Field.Code.ToString()] };
                    break;
                #endregion


                #region Common
                case "QD":
                    BUS.LIST_QDControl qdCtr = new BUS.LIST_QDControl();
                    dt = qdCtr.GetAll_LIST_QD(_db, ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["QD_ID"] };
                    break;
                case "COUNTRY":
                    BUS.COUNTRYControl contryCtr = new BUS.COUNTRYControl();
                    dt = contryCtr.GetAll(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.COUNTRYInfo.Field.COUNTRY_CODE.ToString()] };
                    break;
                case "DB":
                    BUS.DBAControl DBctr = new BUS.DBAControl();
                    dt = DBctr.GetAll(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["DB"] };
                    break;
                case "POD":
                    BUS.PODControl PODctr = new BUS.PODControl();
                    dt = PODctr.GetAll(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["USER_ID"] };
                    break;
                case "POG":
                    BUS.POGControl POGctr = new BUS.POGControl();
                    dt = POGctr.GetAll(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"] };
                    break;
                case "POP":
                    BUS.POPControl POPctr = new BUS.POPControl();
                    dt = POPctr.GetAll(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"], _dsMain.Tables[tableName].Columns["DB"] };
                    break;
                case "DA":
                    BUS.LIST_DAControl dactr = new BUS.LIST_DAControl();
                    dt = dactr.GetAll(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.LIST_DAInfo.Field.DAG_ID.ToString()] };
                    break;
                case "SNS":
                    BUS.SNSControl SNSCtr = new BUS.SNSControl();
                    dt = SNSCtr.GetAll(_db, ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["CODE"] };
                    break;
                case "CAT":
                    BUS.CategoryControl CategoryCtr = new BUS.CategoryControl();
                    dt = CategoryCtr.GetAll(_db, ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["Code"] };
                    break;
                case "DPT":
                    BUS.DepartmentsControl DPTCtr = new BUS.DepartmentsControl();
                    dt = DPTCtr.GetAll(ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["ROLE_ID"], _dsMain.Tables[tableName].Columns["DPT_ID"] };
                    break;
                case "LKC":
                    BUS.LOOKUPControl LOOKUPCtr = new BUS.LOOKUPControl();
                    dt = LOOKUPCtr.GetAll(_db, ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["Code"], _dsMain.Tables[tableName].Columns["Category"] };
                    break;
                case "MLC":
                    BUS.MLCControl MLCCtr = new BUS.MLCControl();
                    dt = MLCCtr.GetAll(_db, ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns["CODE"] };
                    break;
                case "CMD":
                    BUS.LIST_CMDControl CMDCtr = new BUS.LIST_CMDControl();
                    dt = CMDCtr.GetAll(_db, ref sErr);
                    dt.TableName = tableName;
                    if (!IsContainsTables(tableName))
                    {
                        _dsMain.Tables.Add(dt.Copy());

                    }
                    else
                    {
                        _dsMain.Tables.Remove(tableName);
                        _dsMain.Tables.Add(dt.Copy());
                    }
                    if (_dsMain.Tables[tableName].PrimaryKey == null || _dsMain.Tables[tableName].PrimaryKey.Length == 0)
                        _dsMain.Tables[tableName].PrimaryKey = new DataColumn[] { _dsMain.Tables[tableName].Columns[DTO.LIST_CMDInfo.Field.CmdID.ToString()] };
                    break;
                #endregion
            }
        }
        public void InitAnalysis(Control container, DataGridView grid, string func, string[] arrAnal, ref string sErr)
        {
            BUS.MLCControl ctr = new BUS.MLCControl();
            foreach (string anal in arrAnal)
            {
                InitItem(ctr, container, grid, func, anal, ref sErr);
            }
        }
        public void InitAnalysis(Control container, DataGridView grid, string func, string strType, ref string sErr)
        {
            string[] arrAnal = null;
            switch (strType)
            {
                #region Reference
                case "ACC":
                    arrAnal = new string[] { "Accnt00", "Accnt01", "Accnt02", "Accnt03", "Accnt04", "Accnt05", "Accnt06", "Accnt07", "Accnt08", "Accnt09" };
                    InitAnalysis(container, grid, strType, arrAnal, ref sErr);
                    arrAnal = new string[] { "Type" };
                    InitAnalysis(null, grid, strType, arrAnal, ref sErr);
                    break;
                case "EMP":
                    arrAnal = new string[] { "Emp00", "Emp01", "Emp02", "Emp03", "Emp04", "Emp05", "Emp06", "Emp07", "Emp08", "Emp09" };
                    InitAnalysis(container, grid, strType, arrAnal, ref sErr);
                    break;
                case "COT":
                    arrAnal = new string[] { "Contact00", "Contact01", "Contact02", "Contact03", "Contact04", "Contact05", "Contact06", "Contact07", "Contact08", "Contact09" };
                    InitAnalysis(container, grid, strType, arrAnal, ref sErr);
                    break;
                case "TER":
                    arrAnal = new string[] { "Territory00", "Territory01", "Territory02", "Territory03", "Territory04", "Territory05", "Territory06", "Territory07", "Territory08", "Territory09" };
                    InitAnalysis(container, grid, strType, arrAnal, ref sErr);
                    break;
                case "PRO":
                    arrAnal = new string[] { "Product00", "Product01", "Product02", "Product03", "Product04", "Product05", "Product06", "Product07", "Product08", "Product09" };
                    InitAnalysis(container, grid, strType, arrAnal, ref sErr);
                    break;
                case "PRG":
                    arrAnal = new string[] { "Group00", "Group01", "Group02", "Group03", "Group04", "Group05", "Group06", "Group07", "Group08", "Group09" };
                    InitAnalysis(container, grid, strType, arrAnal, ref sErr);
                    break;
                #endregion Reference

                #region Activity
                case "CAL":
                    arrAnal = new string[] { "Call00", "Call01", "Call02", "Call03", "Call04", "Call05", "Call06", "Call07", "Call08", "Call09" };
                    InitAnalysis(container, grid, strType, arrAnal, ref sErr);
                    break;
                #endregion
            }

        }


        private void InitItem(BUS.MLCControl ctr, Control container, DataGridView dgvList, string func, string address, ref string sErr)
        {

            string pathLayout = String.Format("{0}Resources\\Layout\\", ServerPath);
            string pathUserLayout = String.Format("{0}Documents\\Layout\\{1}\\", ServerPath, PODInfo.USER_ID);
            string tmp = "";

            TextBox text = null;
            Label label = null;
            PictureBox picture = null;
            DataGridViewColumn column = null;
            int indexCol = -1;
            ComboBox combo = null;
            Modules.CustomControl.MultiColumnCombo multi = null;
            if (container != null)
            {
                if (container.Controls.ContainsKey(prefixText + address))
                    text = container.Controls[prefixText + address] as TextBox;
                if (container.Controls.ContainsKey(prefixLab + address))
                    label = container.Controls[prefixLab + address] as Label;
                if (container.Controls.ContainsKey(prefixPic + address))
                    picture = container.Controls[prefixPic + address] as PictureBox;
                if (container.Controls.ContainsKey(prefixCom + address))
                    combo = container.Controls[prefixCom + address] as ComboBox;
                if (container.Controls.ContainsKey(prefixMulti + address))
                    multi = container.Controls[prefixMulti + address] as Modules.CustomControl.MultiColumnCombo;
            }
            if (dgvList != null)
            {

                if (dgvList.Columns.Contains(prefixCol + address))
                {
                    column = dgvList.Columns[prefixCol + address];
                    indexCol = column.Index;
                }
            }

            if (ctr.IsExist(DB, String.Format("{0}.{1}", func, address)))
            {
                DTO.MLCInfo inf = ctr.Get(DB, String.Format("{0}.{1}", func, address), ref tmp);

                if (text != null)
                {
                    text.Visible = true;
                    text.Tag = inf.NONVALIDATED;
                }
                if (label != null)
                {
                    label.Visible = true;
                    label.Text = inf.HEADER;
                }
                if (picture != null)
                {
                    picture.Visible = true;
                    picture.Tag = inf.CATEGORY;
                }
                if (combo != null)
                {
                    sErr = AnalysisCombobox(sErr, combo, inf);
                }
                if (multi != null)
                {
                    sErr = AnalysisMultiCombo(sErr, pathLayout, pathUserLayout, multi, inf);
                }
                if (column != null)
                {
                    sErr = AnalysisColumn(sErr, column, multi, inf);
                }
            }
            else if (ctr.IsExist(DB, address))
            {
                DTO.MLCInfo inf = ctr.Get(DB, address, ref tmp);
                if (text != null)
                {
                    text.Visible = true;
                    text.Tag = inf.NONVALIDATED;
                }
                if (label != null)
                {
                    label.Visible = true;
                    label.Text = inf.HEADER;
                }
                if (picture != null)
                {
                    picture.Visible = true;
                    picture.Tag = inf.CATEGORY;
                }
                if (combo != null)
                {
                    sErr = AnalysisCombobox(sErr, combo, inf);
                }
                if (multi != null)
                {
                    sErr = AnalysisMultiCombo(sErr, pathLayout, pathUserLayout, multi, inf);
                }
                if (column != null)
                {
                    sErr = AnalysisColumn(sErr, column, multi, inf);
                }
            }
            else
            {
                if (column != null)
                {
                    column.Visible = false;
                    //((System.ComponentModel.ISupportInitialize)(dgvList)).EndInit();
                }

                if (text != null)
                    text.Visible = false;

                if (label != null)
                    label.Visible = false;

                if (picture != null)
                    picture.Visible = false;

                if (combo != null)
                    combo.Visible = false;

                if (multi != null)
                    multi.Visible = false;

            }
            sErr += tmp;
        }

        private string AnalysisColumn(string sErr, DataGridViewColumn column, Modules.CustomControl.MultiColumnCombo multi, DTO.MLCInfo inf)
        {
            column.HeaderText = inf.HEADER;
            // dgvList.Columns[indexCol].HeaderText = inf.HEADER;// 
            column.Visible = true;
            if (column.GetType() == typeof(DataGridViewComboBoxColumn))
            {
                DataTable dt = null;
                string cate = inf.CATEGORY;
                string code = "";
                dt = GetDataSource(cate, ref code, ref sErr);

                if (code != "")
                {
                    ((DataGridViewComboBoxColumn)column).DisplayMember = "Description";
                    ((DataGridViewComboBoxColumn)column).ValueMember = "Code";
                }
                else if (dt.Columns.Count > 1)
                    ((DataGridViewComboBoxColumn)column).DisplayMember = ((DataGridViewComboBoxColumn)column).ValueMember = dt.Columns[1].ColumnName;
                ((DataGridViewComboBoxColumn)column).DataSource = dt;

            }
            return sErr;
        }

        private string AnalysisMultiCombo(string sErr, string pathLayout, string pathUserLayout, Modules.CustomControl.MultiColumnCombo multi, DTO.MLCInfo inf)
        {
            multi.Visible = true;
            DataTable dt = null;
            string cate = inf.CATEGORY;
            string code = "";
            dt = GetDataSource(cate, ref code, ref sErr);
            if (code != "")
            {
                InitMultiComboBox(multi, new Layout.GridLayout(pathLayout, pathUserLayout, "LKC"), "Description", "Code");
            }
            else
            {
                InitMultiComboBox(multi, new Layout.GridLayout(pathLayout, pathUserLayout, inf.CATEGORY), 1, 0);
            }
            BindingSource bis = multi.Binding as BindingSource;
            if (bis != null)
            {
                bis.DataSource = dt;
                multi.Binding = bis;
            }
            else
                multi.Binding = dt;
            return sErr;
        }

        private string AnalysisCombobox(string sErr, ComboBox combo, DTO.MLCInfo inf)
        {
            combo.Visible = true;
            DataTable dt = null;
            string cate = inf.CATEGORY;
            string code = "";
            dt = GetDataSource(cate, ref code, ref sErr);
            if (code != "")
            {
                combo.ValueMember = DTO.LOOKUPInfo.Field.Code.ToString();
                combo.DisplayMember = DTO.LOOKUPInfo.Field.Description.ToString();
            }
            else
            {
                if (dt.Columns.Count > 2)
                {
                    combo.ValueMember = dt.Columns[1].ColumnName;
                    combo.DisplayMember = dt.Columns[2].ColumnName;
                }
            }

            combo.DataSource = dt;
            return sErr;
        }
        public static double BusinessDaysUntil(DateTime startD, DateTime endD)
        {
            double calcBusinessDays = 1 + ((endD - startD).TotalDays * 5 - (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;
            if ((int)endD.DayOfWeek == 6) calcBusinessDays--;
            if ((int)startD.DayOfWeek == 0) calcBusinessDays--;
            return calcBusinessDays;
        }
        public DataTable GetDataSource(string cate, ref string code, ref string sErr)
        {
            DataTable dt = new DataTable();
            BUS.CategoryControl cateCtr = new BUS.CategoryControl();
            DTO.CategoryInfo cateinfo = cateCtr.Get(DB, cate, ref sErr);
            code = cateinfo.Code;
            if (code != "")
            {
                if (cateinfo.QdCode == "")
                {
                    if (!IsContainsTables("LKC"))
                        LoadDataTable("LKC");
                    DataRow[] arr = _dsMain.Tables["LKC"].Select(String.Format("Category='{0}'", cate));
                    dt = _dsMain.Tables["LKC"].Clone();
                    foreach (DataRow row in arr)
                    {
                        dt.Rows.Add(row.ItemArray);
                    }
                }
                else
                {
                    dt = LoadQDSource(DB, cateinfo);
                }

            }
            else
            {
                if (!IsContainsTables(cate))
                    LoadDataTable(cate);
                dt = GetTable(cate);
            }
            return dt;
        }
        public DataTable GetDataSource(string cate, ref string code, Dictionary<string, string> myparams, ref string sErr)
        {
            DataTable dt = new DataTable();
            BUS.CategoryControl cateCtr = new BUS.CategoryControl();
            DTO.CategoryInfo cateinfo = cateCtr.Get(DB, cate, ref sErr);
            code = cateinfo.Code;
            if (code != "")
            {
                if (cateinfo.QdCode == "")
                {
                    if (!IsContainsTables("LKC"))
                        LoadDataTable("LKC");
                    DataRow[] arr = _dsMain.Tables["LKC"].Select(String.Format("Category='{0}'", cate));
                    dt = _dsMain.Tables["LKC"].Clone();
                    foreach (DataRow row in arr)
                    {
                        dt.Rows.Add(row.ItemArray);
                    }
                }
                else
                {
                    dt = LoadQDSource(DB, cateinfo, myparams);
                }

            }
            else
            {
                if (!IsContainsTables(cate))
                    LoadDataTable(cate);
                dt = GetTable(cate);
            }
            return dt;
        }
        public void AnalysisValidated(TextBox text, Control container, ErrorProvider erro, ref string sErr)
        {
            if (text != null)
            {
                if (text.Tag.ToString() != "Y")
                {
                    string key = text.Name.Replace(prefixText, prefixPic);
                    string cate = container.Controls[key].Tag.ToString();
                    BUS.CategoryControl cateCtr = new BUS.CategoryControl();
                    DTO.CategoryInfo cateinfo = cateCtr.Get(DB, cate, ref sErr);
                    if (cateinfo.QdCode == "")
                    {
                        if (!IsContainsTables("LKC"))
                            LoadDataTable("LKC");
                        DataRow[] arr = _dsMain.Tables["LKC"].Select(String.Format("Category='{0}'", cate));
                        bool flag = false;
                        foreach (DataRow row in arr)
                        {
                            if (row[row.Table.PrimaryKey[0]].ToString() == text.Text)
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            erro.SetIconAlignment(text, ErrorIconAlignment.MiddleLeft);
                            erro.SetError(text, "Input data is not in list");
                        }
                        else erro.SetError(text, "");
                    }
                    else
                    {
                        using (DataTable dt = LoadQDSource(DB, cateinfo))
                        {
                            bool flag = false;
                            foreach (DataRow row in dt.Rows)
                            {
                                if (row["Code"].ToString() == text.Text)
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag)
                            {
                                erro.SetIconAlignment(text, ErrorIconAlignment.MiddleLeft);
                                erro.SetError(text, "Input data is not in list");
                            }
                            else
                                erro.SetError(text, "");
                        }
                    }
                }
                else erro.SetError(text, "");
            }
        }
        public static void AnalysisClicked(PictureBox pb, Control container, ErrorProvider error)
        {
            if (pb != null)
            {
                string key = pb.Name.Replace(prefixPic, prefixText);
                using (Forms.frmLKC frm = new Forms.frmLKC(pb.Tag.ToString()))
                {
                    frm.FormClosed += (form, args) =>
                    {
                        if (((Forms.frmLKC)form).DialogResult == DialogResult.OK)
                        {
                            if (((Forms.frmLKC)form).ReturnValue.Table.PrimaryKey != null)
                                container.Controls[key].Text = ((Forms.frmLKC)form).ReturnValue[((Forms.frmLKC)form).ReturnValue.Table.PrimaryKey[0]].ToString();
                            else
                            {
                                container.Controls[key].Text = ((Forms.frmLKC)form).ReturnValue[0].ToString();
                            }
                            error.SetError(container.Controls[key], "");
                        }
                    };
                    frm.ShowDialog();
                }
            }
        }
        public void PrintDataSet(DataSet ds, string _strType)
        {
            string tempPath = Context.HttpContext.Request.MapPath("/") + Properties.Settings.Default.ReportTemplatePath;
            string repotPath = Context.HttpContext.Request.MapPath("/") + Properties.Settings.Default.ReportPath;
            string logPath = Context.HttpContext.Request.MapPath("/") + Properties.Settings.Default.ErroLogPath;
            Report.ReportGenerator rg = new Report.ReportGenerator(ds, _strType, DB, Properties.Settings.Default.TVCConnectStringDes, tempPath, repotPath, logPath);
            rg.ValueList.Add("EmployeeID", PODInfo.EMP_ID);
            FlexCel.Core.ExcelFile file = rg.CreateReport();
            MemoryStream ms = new MemoryStream();

            file.Save(ms);

            DownloadGateway myDownload = new DownloadGateway(ms, _strType + ".xls");

            myDownload.ContentType = "application/vnd.ms-excel";
            myDownload.StartDownload(this);

            ms.Close();
        }



        public static DataTable GetTableStruct(string _strType)
        {
            DataTable dt = null;
            //if (IsContainsTables(_strType))
            //    dt =  GetTable(_strType).Clone();
            //else
            //{
            dt = BUS.CommonControl.GetTableStruct(_strType) as DataTable;
            //}
            //dt.Columns.Add("Code");
            return dt;
        }

        public DataTable GetTable(string _strType)
        {
            //if (_dsMain.Tables.Contains(_strType))
            return _dsMain.Tables[_strType];
            //return null;
        }
        public DataTable GetDuplicateTable(string _strType)
        {
            return _dsMain.Tables[_strType].Copy();
        }

        class ComboBoxItem
        {

            public string Name { get; set; }

            public double Value { get; set; }

        }

        public bool IsContainsTables(string type)
        {
            return _dsMain.Tables.Contains(type);
        }

        public bool UpdateRecord(string _strType, object[] arrObj, LoadOption bWrite)
        {
            bool a = IsExist(_dsMain.Tables[_strType], arrObj);
            _dsMain.Tables[_strType].LoadDataRow(arrObj, bWrite);
            return a;
        }

        private bool IsExist(DataTable dataTable, object[] arrObj)
        {
            if (dataTable.PrimaryKey == null || dataTable.PrimaryKey.Length == 0)
            {
                foreach (DataRow row in dataTable.Rows)
                    if (row.ItemArray == arrObj)
                        return true;
            }
            else
            {
                DataRow newRow = dataTable.NewRow();
                newRow.ItemArray = arrObj;
                object[] key = new object[dataTable.PrimaryKey.Length];
                int i = 0;
                foreach (DataColumn col in dataTable.PrimaryKey)
                    key[i++] = newRow[col];

                return dataTable.Rows.Contains(key);
            }
            return false;

        }
        public bool UpdateRecord(string _strType, DataRow aRow, LoadOption bWrite)
        {
            bool anewflag = true;
            foreach (DataRow row in _dsMain.Tables[_strType].Rows)
            {
                bool flag = true;
                foreach (DataColumn col in _dsMain.Tables[_strType].PrimaryKey)
                {
                    if (row[col.ColumnName].ToString() != aRow[col.ColumnName].ToString())
                        flag = false;
                }
                if (flag)
                {
                    anewflag = false;
                    foreach (DataColumn col in _dsMain.Tables[_strType].Columns)
                    {
                        if (aRow.Table.Columns.Contains(col.ColumnName))
                            row[col.ColumnName] = aRow[col.ColumnName];
                    }

                    return false;
                }

            }
            if (anewflag)
            {
                DataRow newRow = _dsMain.Tables[_strType].NewRow();
                foreach (DataColumn col in _dsMain.Tables[_strType].Columns)
                {
                    if (aRow.Table.Columns.Contains(col.ColumnName))
                        newRow[col.ColumnName] = aRow[col.ColumnName];
                }
                _dsMain.Tables[_strType].Rows.InsertAt(newRow, 0);
                return true;
            }
            return false;
        }
        public void UpdateField(string _strType, DataRow aRow, string fieldName, string value)
        {
            bool anewflag = true;
            if (_dsMain.Tables[_strType].Columns.Contains(fieldName))
            {
                foreach (DataRow row in _dsMain.Tables[_strType].Rows)
                {
                    bool flag = true;
                    foreach (DataColumn col in _dsMain.Tables[_strType].PrimaryKey)
                    {
                        if (row[col.ColumnName] != aRow[col.ColumnName])
                            flag = false;
                    }
                    if (flag)
                    {
                        row[fieldName] = value;
                        break;
                    }
                }
            }
        }
        public void InitMultiComboBox(TVC.Modules.CustomControl.MultiColumnCombo multiCBO, GridLayout layout, int displayCol, int valueCol)
        {
            string desc = "";
            if (displayCol < layout.LColumn.Count)
                desc = layout.LColumn[displayCol].DataPropertyName;
            string val = "";
            if (valueCol < layout.LColumn.Count)
                val = layout.LColumn[valueCol].DataPropertyName;
            InitMultiComboBox(multiCBO, layout, desc, val);
        }
        public void InitMultiComboBox(TVC.Modules.CustomControl.MultiColumnCombo multiCBO, GridLayout layout, string DisplayField, string ValueField)
        {
            multiCBO.MainForm = this;
            multiCBO.Lookup = layout.Type;
            multiCBO.Layout = layout;
            multiCBO.DisplayField = DisplayField;
            multiCBO.ValueField = ValueField;
        }

        //public void ListComboBox(TVC.Modules.CustomControl.ComboboxList multiCBO, GridLayout layout, int Displaycol, int Valuecol)
        //{
        //    multiCBO.ControlSize = 300; // multiCBO.Width;
        //    List<string> lHeader = new List<string>();
        //    List<bool> lVisble = new List<bool>();
        //    List<int> lSize = new List<int>();
        //    List<string> lData = new List<string>();
        //    List<Type> lType = new List<Type>();
        //    foreach (Layout.GridLayout.LayoutColumn col in layout.LColumn)
        //    {
        //        lHeader.Add(col.HeaderText);
        //        lVisble.Add(col.Visible);
        //        lSize.Add(col.Size > 200 ? 200 : col.Size);
        //        lType.Add(col.DataType);
        //        lData.Add(col.DataPropertyName);
        //    }
        //    multiCBO.ColumnHeader = lHeader;
        //    multiCBO.ColumnVisible = lVisble;
        //    multiCBO.ColumnWidths = lSize;
        //    multiCBO.ColumnDataType = lType;
        //    multiCBO.ColumnDataPropertyName = lData;

        //    multiCBO.RowData = new List<string>();
        //    //Can have up to three filters -1 = disable
        //    multiCBO.DisplayColumn = Displaycol;
        //    multiCBO.ValueColumn = Valuecol;
        //    multiCBO.AutoScroll = true;
        //    //Initialise filters
        //    //multiCBO.Binding = bisComboPOS;
        //}

        public void RemoveRecord(string _strType, DataRow dataRow)
        {
            _dsMain.Tables[_strType].Rows.Remove(dataRow);
        }

        public string GetTypeEvent(Color color)
        {
            string sErr = "";
            BUS.LOOKUPControl ctr = new BUS.LOOKUPControl();
            using (DataTable dt = ctr.GetByCategory(DB, "ACTIVE", ref sErr))
            {
                foreach (DataRow row in dt.Rows)
                {
                    Color tmp = Color.White;
                    try
                    {
                        tmp = Color.FromName(row[DTO.LOOKUPInfo.Field.Description1.ToString()].ToString());
                        if (tmp == color)
                            return row[DTO.LOOKUPInfo.Field.Code.ToString()].ToString();
                    }
                    catch
                    {
                    }
                }
            }

            return "";
        }
        public Color GetColorEvent(String type)
        {
            string sErr = "";
            BUS.LOOKUPControl ctr = new BUS.LOOKUPControl();
            DTO.LOOKUPInfo info = ctr.Get(DB, type, "ACTIVE", ref sErr);
            if (info.Description1 != "")
            {
                try
                {
                    string[] rgb = info.Description1.Split(',');
                    if (rgb != null && rgb.Length == 3)
                        return Color.FromArgb(Convert.ToInt32(rgb[0]), Convert.ToInt32(rgb[1]), Convert.ToInt32(rgb[2]));
                    else
                        return Color.FromName(info.Description1);
                }
                catch { }
            }
            return Color.White;
        }



        public static bool IsContainsPlan(ScheduleBox demoScheduleBox, ScheduleBoxEvent aEvent)
        {

            return false;
        }
        public static bool IsContainsPlan(ScheduleBox demoScheduleBox, string id)
        {

            return false;
        }
        public static bool IsContainsAct(ScheduleBox demoScheduleBox, string id)
        {

            return false;
        }



        public static string Base64ToString(string b64)
        {
            byte[] b = Convert.FromBase64String(b64);
            return (System.Text.Encoding.UTF8.GetString(b));
        }



        public bool IsContainsKey(string lookup, string p)
        {
            if (!IsContainsTables(lookup))
            {
                LoadDataTable(lookup);
            }
            using (DataTable dt = GetTable(lookup))
            {
                foreach (DataRow row in dt.Rows)
                {
                    if (row[dt.PrimaryKey[0]].ToString() == p)
                        return true;
                }
            }
            return false;
        }
        public DataTable GetCategory(BUS.CategoryControl cateCtr, DTO.CategoryInfo cateinfo)
        {
            DataTable adt = null;
            if (cateinfo.QdCode == "")
            {
                if (!IsContainsTables("LKC"))
                    LoadDataTable("LKC");
                DataRow[] arr = GetTable("LKC").Select(String.Format("Category='{0}'", cateinfo.Code));
                adt = GetTable("LKC").Clone();
                foreach (DataRow arow in arr)
                {
                    adt.Rows.Add(arow.ItemArray);
                }
            }
            else
            {
                adt = LoadQDSource(DB, cateinfo);
            }
            return adt;
        }
        #endregion My Method


        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // MainForm
            // 
            this.DockPadding.All = 3;
            this.ResumeLayout(false);
        }

        public override bool IsPermis(int id)
        {
            return IsPermis(id, Permission);
        }
        public static bool IsPermis(int id, string permission)
        {
            if (id >= permission.Length || permission[id] == 'Y')
                return true;
            return false;
        }
        public static bool IsPermis(string id, string permission)
        {
            if (id == null || Convert.ToInt32(id) >= permission.Length || permission[Convert.ToInt32(id)] == 'Y')
                return true;
            return false;
        }

        public bool IsLockAct(DateTime dateTime)
        {
            //if (dateTime < Events.actMinDate)// || dateTime > Events.actMinDate
            //{
            //    return true;
            //}
            return false;
        }
        public bool IsLockPln(DateTime dateTime)
        {
            //if (dateTime < Events.planMinDate)
            //{
            //    return true;
            //}
            return false;
        }
        #region UpdateLanguage
        public void UpdateControlLanguage(string type, object obj)
        {
            if (obj is Control)
            {
                Control control = obj as Control;

                Modules.Ddb.frmInputData frm = new Modules.Ddb.frmInputData();
                frm.Default = control.Text;
                frm.FormClosed += (form, args) =>
                {
                    if (((Form)form).DialogResult == DialogResult.OK)
                    {
                        control.Text = frm.valuereturn;
                        clsConfigurarion.SetLabel(type, control, Language);
                    }
                };
                frm.ShowDialog();
            }
            else if (obj is DataGridViewColumn)
            {
                DataGridViewColumn col = obj as DataGridViewColumn;
                Modules.Ddb.frmInputData frm = new Modules.Ddb.frmInputData();
                frm.Default = col.HeaderText;
                frm.FormClosed += (form, args) =>
                {
                    if (((Form)form).DialogResult == DialogResult.OK)
                    {
                        col.HeaderText = frm.valuereturn;
                        clsConfigurarion.SetLabel(type, col.Name, col.HeaderText, Language);
                    }
                };
                frm.ShowDialog();
            }
        }
        public void UpdateControlLanguage(string type, object obj, string key)
        {
            if (obj is Control)
            {
                Control control = obj as Control;

                Modules.Ddb.frmInputData frm = new Modules.Ddb.frmInputData();
                frm.Default = control.Text;
                frm.FormClosed += (form, args) =>
                {
                    if (((Form)form).DialogResult == DialogResult.OK)
                    {
                        control.Text = frm.valuereturn;
                        clsConfigurarion.SetLabel(type, key, control.Text, Language);
                    }
                };
                frm.ShowDialog();
            }
            else if (obj is DataGridViewColumn)
            {
                DataGridViewColumn col = obj as DataGridViewColumn;
                Modules.Ddb.frmInputData frm = new Modules.Ddb.frmInputData();
                frm.Default = col.HeaderText;
                frm.FormClosed += (form, args) =>
                {
                    if (((Form)form).DialogResult == DialogResult.OK)
                    {
                        col.HeaderText = frm.valuereturn;
                        clsConfigurarion.SetLabel(type, key, col.HeaderText, Language);
                    }
                };
                frm.ShowDialog();
            }
        }
        #endregion



        public void RemoveRecord(string _strType, string field, string value)
        {
            if (_dsMain.Tables.Contains(_strType) && _dsMain.Tables[_strType].Columns.Contains(field))
            {
                for (int i = 0; i < _dsMain.Tables[_strType].Rows.Count; i++)
                {
                    DataRow row = _dsMain.Tables[_strType].Rows[i];
                    if (row[field].ToString() == value)
                    {
                        _dsMain.Tables[_strType].Rows.Remove(row);
                    }
                }
            }

        }
        [SecuritySafeCritical]
        public object Eval(string formula)
        {
            //try
            //{
            //    CsEvaluator evaluator = CsEval.GetEvaluator(formula);
            //    CsEval.EvalEnvironment = this;
            //    return CsEval.Eval(evaluator);
            //}
            //catch {
            return null;
            //}
        }


        public Control mme { get; set; }

        public Control imr { get; set; }
        List<string[]> _curDockLink = new List<string[]>();

        internal static string GetCurrentDocLink(string _trans_type)
        {
            if (Current == null) return null;
            foreach (string[] x in Current._curDockLink)
            {
                if (x[0] == _trans_type) return x[1];
            }
            return null;
        }
        internal static void SetCurrentDocLink(string _trans_type, string view)
        {
            if (Current == null) return;
            bool isExists = false;
            for (int i = Current._curDockLink.Count - 1; i >= 0; i--)
            {
                object[] x = Current._curDockLink[i];
                if (x[0] == _trans_type)
                {
                    if (view != null) x[1] = view;
                    else Current._curDockLink.RemoveAt(i);
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
            {
                Current._curDockLink.Add(new string[] { _trans_type, view });

            }
        }
    }
}
